import React, { useState } from 'react';
import { Table, Icon } from 'antd';
import PropTypes from 'prop-types';
import _ from 'lodash';
import { LEVEL_TEXT, LEVEL_COLOR } from '@util/constants';
import OneDayDetail from '@components/oneday-detail-info';
import Tag from '@components/tag';
import './index.less';
import URL from 'url';
// 漏洞列表组件
function OneDayTable(props) {
  const { onedayList = [], pagination = {}, onTableChange = () => {} } = props;
  const [expandedRowKeys, setExpandedRowKeys] = useState([]);

  const unExpand = id => {
    const newExpandedRowKeys = expandedRowKeys.filter(key => key !== id);
    setExpandedRowKeys(newExpandedRowKeys);
  };

  const renderExpandedRow = row => {
    return (
      <div className="expand-row-wapper">
        <OneDayDetail data={row} />
        <span className="un-expan" onClick={() => unExpand(row._id)}>
          <Icon type="arrow-up" />
          收起
        </span>
      </div>
    );
  };

  const onExpandedRowsChange = keys => {
    setExpandedRowKeys(keys);
  };

  const columns = [
    { title: '漏洞名称', dataIndex: 'onedayDetailOid.name' },
    {
      title: '漏洞等级',
      dataIndex: 'onedayDetailOid.level',
      className: 'vul-level',
      render: level => <Tag color={LEVEL_COLOR[level]} value={LEVEL_TEXT[level] || '未知'} />
    },
    {
      title: '漏洞URL',
      dataIndex: 'verifyInfo.URL',
      className: 'vul-url',
      width: 300,
      render: (url, row) => {
        let Url;
        if (row.nuclei) {
          Url = row.nuclei['matched-at'];
        } else if (row.ps3) {
          Url = _.get(row, 'ps3.verifyInfo.URL');
        } else if (row.nscan) {
          Url = _.get(row, 'nscan.detail.url');
        } else {
          Url = url;
        }
        return Url ? (
          <a
            href={Url}
            onClick={e => e.stopPropagation()}
            target="_blank"
            rel="noopener noreferrer"
          >
            {Url}
          </a>
        ) : (
          '-'
        );
      }
    },
    {
      title: '漏洞端口',
      dataIndex: 'verifyInfo.Port',
      className: 'vul-port',
      render: (url, row) => {
        let valPort = '';
        // 每个引擎数据类型不一样
        if (row.nuclei) {
          let url = row.nuclei['matched-at'];
          const info = URL.parse(url);
          valPort = info.port;
        } else if (row.ps3) {
          valPort = _.get(row, 'ps3.verifyInfo.Port');
        } else if (row.nscan) {
          const traffics = _.get(row, 'nscan.detail.traffics');
          if (traffics) {
            let rowIndex = traffics.find(r => _.get(r, 'request', null));
            let rowPort = _.get(rowIndex, 'request.port', null);
            if (rowPort) {
              valPort = rowPort;
            }
            const host = _.get(rowIndex, 'request.headers.host', null);
            if (host) {
              const info = URL.parse(host);
              if (info.port) {
                valPort = info.port;
              }
            }
          }
        }
        return valPort ? valPort : _.get(row, 'portOid.port') ? _.get(row, 'portOid.port') : '-';
      }
    },
    {
      title: '影响组件',
      className: 'affect-component',
      dataIndex: 'onedayDetailOid.affected',
      render: item => item || '-'
    },
    {
      title: '波及资产地址',
      dataIndex: 'targetInfoOid',
      className: 'affect-asset',
      render: site => {
        const { ip, url, name, ipv6 } = site || {};
        const addr = [name, ip, url, ipv6].filter(Boolean);

        const filter = [
          ip ? `exact:ip="${ip}"` : '',
          url ? `exact:url="${url}"` : '',
          name ? `exact:name="${name}"` : '',
          ipv6 ? `exact:name="${ipv6}"` : ''
        ]
          .filter(Boolean)
          .join(' && ');

        const addressStr = addr
          .map((item, index) => {
            if (index) {
              return ` (${item})`;
            }
            return item;
          })
          .join('');

        return addr.length ? (
          <a
            href={`/asset-manage?${encodeURIComponent(filter)}`}
            onClick={e => e.stopPropagation()}
            target="_blank"
            rel="noopener noreferrer"
          >
            {addressStr}
          </a>
        ) : (
          '-'
        );
      }
    }
  ];

  return (
    <div className="oneday-table">
      <Table
        rowKey={'_id'}
        columns={columns}
        dataSource={onedayList}
        pagination={pagination}
        onChange={onTableChange}
        expandRowByClick={true}
        expandedRowRender={renderExpandedRow}
        expandedRowKeys={expandedRowKeys}
        onExpandedRowsChange={onExpandedRowsChange}
        rowClassName={record => {
          if (expandedRowKeys.indexOf(record._id) !== -1) {
            return 'expaned';
          }
        }}
      />
    </div>
  );
}

OneDayTable.propTypes = {
  onedayList: PropTypes.array,
  pagination: PropTypes.object,
  onTableChange: PropTypes.func
};

export default OneDayTable;
